// cloudfunctions/getBills/index.js
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

/**
 * 获取账单列表云函数
 */
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID

  try {
    const {
      page = 1,
      limit = 20,
      startDate,
      endDate,
      type,
      category,
      categoryId,
      sortBy = 'date',
      sortOrder = 'desc',
      keyword
    } = event

    // 参数验证
    if (page < 1 || limit < 1 || limit > 100) {
      return {
        success: false,
        code: 1001,
        message: '分页参数无效'
      }
    }

    // 构建查询条件
    const whereCondition = {
      _openid: openid,
      isDeleted: false
    }

    // 日期范围筛选
    if (startDate && endDate) {
      whereCondition.date = _.gte(startDate).and(_.lte(endDate))
    } else if (startDate) {
      whereCondition.date = _.gte(startDate)
    } else if (endDate) {
      whereCondition.date = _.lte(endDate)
    }

    // 类型筛选
    if (type && ['income', 'expense'].includes(type)) {
      whereCondition.type = type
    }

    // 分类筛选
    if (category) {
      whereCondition.category = category
    }
    if (categoryId) {
      whereCondition.categoryId = categoryId
    }

    // 关键词搜索（搜索备注和分类）
    if (keyword) {
      whereCondition._ = _.or([
        { note: db.RegExp({ regexp: keyword, options: 'i' }) },
        { category: db.RegExp({ regexp: keyword, options: 'i' }) }
      ])
    }

    // 构建排序条件
    const sortField = ['date', 'amount', 'createTime'].includes(sortBy) ? sortBy : 'date'
    const sortDirection = sortOrder === 'asc' ? 'asc' : 'desc'

    // 计算跳过的记录数
    const skip = (page - 1) * limit

    // 查询账单列表
    const billsQuery = db.collection('bills')
      .where(whereCondition)
      .orderBy(sortField, sortDirection)
      .skip(skip)
      .limit(limit)

    // 如果按日期排序，添加创建时间作为第二排序字段
    if (sortField === 'date') {
      billsQuery.orderBy('createTime', sortDirection)
    }

    const billsResult = await billsQuery.get()

    // 查询总数
    const countResult = await db.collection('bills')
      .where(whereCondition)
      .count()

    const total = countResult.total
    const totalPages = Math.ceil(total / limit)

    // 计算统计信息
    const statsQuery = await db.collection('bills')
      .where(whereCondition)
      .get()

    let totalIncome = 0
    let totalExpense = 0
    let count = 0

    statsQuery.data.forEach(bill => {
      count++
      if (bill.type === 'income') {
        totalIncome += bill.amount
      } else {
        totalExpense += bill.amount
      }
    })

    const balance = totalIncome - totalExpense

    // 处理账单数据，添加分类颜色等信息
    const bills = await Promise.all(billsResult.data.map(async (bill) => {
      // 获取分类信息
      let categoryInfo = null
      if (bill.categoryId) {
        try {
          const categoryResult = await db.collection('categories').doc(bill.categoryId).get()
          if (categoryResult.data) {
            categoryInfo = categoryResult.data
          }
        } catch (error) {
          console.warn('获取分类信息失败:', error)
        }
      }

      return {
        ...bill,
        categoryColor: categoryInfo ? categoryInfo.color : '#1AAD19',
        categoryIcon: categoryInfo ? categoryInfo.icon : 'other'
      }
    }))

    return {
      success: true,
      code: 0,
      message: '获取账单列表成功',
      data: {
        bills: bills,
        pagination: {
          page: page,
          limit: limit,
          total: total,
          totalPages: totalPages,
          hasNext: page < totalPages,
          hasPrev: page > 1
        },
        summary: {
          totalIncome: Number(totalIncome.toFixed(2)),
          totalExpense: Number(totalExpense.toFixed(2)),
          balance: Number(balance.toFixed(2)),
          count: count
        }
      }
    }

  } catch (error) {
    console.error('获取账单列表失败:', error)
    return {
      success: false,
      code: 5001,
      message: '获取账单列表失败，请重试',
      error: error.message
    }
  }
}